package com.ocom.websocket.websocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.tio.server.ServerTioConfig;
import org.tio.websocket.server.WsServerStarter;

import java.io.IOException;


@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

//	@Value("${websocket.port}")
//	String port;

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		// 配置客户端尝试连接地址
		registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
	}

	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		// 设置广播节点
		registry.enableSimpleBroker("/topic", "/user");
		// 客户端向服务端发送消息需有/app 前缀
		registry.setApplicationDestinationPrefixes("/app");
		// 指定用户发送（一对一）的前缀 /user/
		registry.setUserDestinationPrefix("/user/");

	}

	/**
	 * 注入消息处理器
	 */
	@Autowired
	private MyHandler myWsMsgHandler;

	/**
	 * 启动类配置
	 *
	 * @return
	 * @throws IOException
	 */
	@Bean
	public WsServerStarter wsServerStarter() throws IOException {
		// 设置处理器
		WsServerStarter wsServerStarter = new WsServerStarter(9348, myWsMsgHandler);
		// 获取到ServerTioConfig
		ServerTioConfig serverTioConfig = wsServerStarter.getServerTioConfig();
		// 设置心跳超时时间，默认：1000 * 120
		serverTioConfig.setHeartbeatTimeout(1000 * 120);
		// 启动
		wsServerStarter.start();
		return wsServerStarter;
	}

}